<template>
  <el-card>
    <el-button type="primary" @click="openAddRoleDialog" style="margin-bottom: 8px">添加角色</el-button>

    <el-table :data="roles" style="width: 100%" border>
      <el-table-column label="角色序号" prop="id" width="100px"/>
      <el-table-column label="角色名称" prop="name" width="200px"/>
      <el-table-column label="权限" prop="permissions" />

      <el-table-column label="操作" width="150px">
        <template #default="scope">
          <el-button size="small" @click="editRole(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteRoleHandler(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 编辑/新增角色弹窗 -->
  <el-dialog v-model="showDialog" title="编辑角色">
    <el-collapse v-model="activeName" accordion>
      <el-collapse-item title="权限编辑" name="1">
        <el-form :model="selectedRole" label-width="120px" ref="roleFormRef">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="selectedRole.name" />
          </el-form-item>

          <el-form-item label="分配权限">
            <el-transfer
                v-model="selectedRole.permissions"
                :data="allPermissions"
                filterable
                filter-placeholder="请输入权限名称"
                :titles="['可选权限', '已分配权限']"
                :props="{ key: 'key', label: 'label' }"
            >
              <template #left-empty>
                <el-empty :image-size="60" description="无可用权限" />
              </template>
              <template #right-empty>
                <el-empty :image-size="60" description="未分配权限" />
              </template>
            </el-transfer>
          </el-form-item>
        </el-form>

        <div style="text-align: right">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="saveRoleChanges">保存</el-button>
        </div>
      </el-collapse-item>

      <el-collapse-item title="资源授权" name="2">
        <el-table :data="resources" style="width: 100%">
          <el-table-column label="授权类型" prop="type" />
          <el-table-column label="关联索引" prop="resourceIndex" />
          <el-table-column align="right">
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getRoles,
  addRole,
  updateRole,
  deleteRole,
  getRolePermissions,
  getRoleResources,
  deleteRoleResource
} from '@/apps/admin/utils/rolesApi.js'

const roles = ref([])
const showDialog = ref(false)
const selectedRole = ref({ id: null, name: '', permissions: [] })
const allPermissions = ref([])
const resources = ref([])
const activeName = ref('1')

// 获取权限
const fetchAllPermissions = async () => {
  try {
    const res = await getRolePermissions()
    if (res.code !== 200) {
      ElMessage.error(res.msg || '获取权限失败')
      return
    }
    allPermissions.value = res.data.map(p => ({
      key: p.value,
      label: p.desc
    }))
  } catch (error) {
    ElMessage.error(error?.response?.data?.msg || '获取权限失败')
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await getRoles()
    if (res["code"] !== 200) {
      ElMessage.error(res.msg || '获取角色失败')
      return
    }
    roles.value = res.data
  } catch (error) {
    ElMessage.error(error?.response?.data?.msg || '获取角色失败')
  }
}

// 获取资源授权
const updateRoleResources = async (roleId) => {
  try {
    const res = await getRoleResources(roleId)
    if (res.code !== 200) {
      ElMessage.error(res.msg || '获取资源失败')
      return
    }
    resources.value = res.data
  } catch (error) {
    ElMessage.error(error?.response?.data?.msg || '获取资源失败')
  }
}

// 打开新增角色对话框
const openAddRoleDialog = () => {
  selectedRole.value = { id: null, name: '', permissions: [] }
  resources.value = []
  showDialog.value = true
}

// 编辑角色
const editRole = async (role) => {
  selectedRole.value = { ...role }
  if (!Array.isArray(selectedRole.value.permissions)) {
    selectedRole.value.permissions = []
  }
  await updateRoleResources(role.id)
  showDialog.value = true
}

// 保存角色（新增或更新）
const saveRoleChanges = async () => {
  try {
    if (!selectedRole.value.name) {
      return ElMessage.error('角色名称不能为空')
    }

    let res
    if (selectedRole.value.id) {
      res = await updateRole({
        id: selectedRole.value.id,
        name: selectedRole.value.name,
        permissions: selectedRole.value.permissions
      })
    } else {
      res = await addRole(selectedRole.value)
    }

    if (res.code !== 200) {
      ElMessage.error(res.msg || '保存角色失败')
      return
    }

    await fetchRoles()
    showDialog.value = false
    ElMessage.success('角色已保存')
  } catch (error) {
    ElMessage.error(error?.response?.data?.msg || '保存角色失败')
  }
}

// 删除角色
const deleteRoleHandler = async (role) => {
  try {
    const res = await deleteRole(role.id)
    if (res.code !== 200) {
      ElMessage.error(res.msg || '删除角色失败')
      return
    }
    roles.value = roles.value.filter(r => r.id !== role.id)
    ElMessage.success('角色已删除')
  } catch (error) {
    ElMessage.error(error?.response?.data?.msg || '删除角色失败')
  }
}

// 删除授权资源
const handleDelete = async (resource) => {
  try {
    const res = await deleteRoleResource(resource.id)
    if (res.code !== 200) {
      ElMessage.error(res.msg || '删除资源授权失败')
      return
    }
    ElMessage.success('资源授权已删除')
    await updateRoleResources(selectedRole.value.id)
  } catch (error) {
    ElMessage.error(error?.response?.data?.msg || '删除资源授权失败')
  }
}

onMounted(() => {
  fetchRoles()
  fetchAllPermissions()
})
</script>

<style scoped>
.upload-demo i {
  font-size: 24px;
}
</style>
